// 接口地址
var HOST = 'http://47.94.130.207:8084/'
//测试
// var HOST = 'http://127.0.0.1:8084/'
// 创建axios实例
var service = axios.create({
    baseURL: HOST, // api 的 base_url
    timeout: 100000 // 请求超时时间
})
service.defaults.headers['Content-Type'] = 'application/json; charset=utf-8';

// request拦截器
service.interceptors.request.use(
    config => {
        if (layui.data('TOKEN')) {
            if (config.url.indexOf('auth') === -1) {
                // 让每个请求携带自定义token
                config.headers['Authorization'] = layui.data("TOKEN").TOKEN
            }
        }
        config.headers['Content-Type'] = 'application/json'
        // 刷新token
        return config
    },
    error => {
        Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
        const code = response.status
        if (code < 200 || code > 300) {
            layer.msg(response.data.msg, {offset: '45vh', icon: 5, time: 2000});
            return Promise.reject('error')
        } else {
            return response.data
        }
    },
    error => {
        let code = 0
        try {
            code = error.response.status
            if (code === 401) {
                layer.open({
                    type: 1,
                    title: false, //不显示标题栏
                    closeBtn: false,
                    area: '300px;',
                    shade: 0.8,
                    id: 'LAY_layuipro',
                    btn: ['重新登录'],
                    btnAlign: 'c',
                    moveType: 1,
                    content: '<div style="padding: 60px 30px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">您的登录信息已失效，请重新登录！</div>',
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        btn.find('.layui-layer-btn0').attr({
                            href: '../login/login.html'
                        });
                    }
                });
                return Promise.reject(error.response.data)
            }
        } catch (e) {
            if (error.toString().indexOf('Error: timeout') !== -1) {
                layer.msg('网络请求超时',{offset: '45vh', icon: 5, time: 2000});
                return Promise.reject(error.response.data)
            }
            if (error.toString().indexOf('Error: Network Error') !== -1) {
                layer.msg('网络请求错误', {offset: '45vh', icon: 5, time: 2000});
                return Promise.reject(error.response.data)
            }
        }
        return Promise.reject(error.response.data)
    }
)
